<template>
    <div class="comment">
      <!-- 显示用户名 -->
      <div class="comment-author">
        
        <p>{{ username }}回复{{ usernaem2 }}:{{ comment.content }}</p>
      </div>
      
      <small class="comment-time">{{ formattedTime }}</small>
      <div>
        <el-button @click="toggleReplyInput" size="mini">回复</el-button>
      </div>
      <!-- 嵌套评论 -->
      <div v-if="comment.replies" class="nested-comment">
        <CommentItem
          v-for="reply in comment.replies"
          :key="reply.ID"
          :comment="reply"
          @reply="handleNestedReply"
        />
      </div>
  
      <!-- 回复输入框 -->
      <div v-if="showReplyInput" class="reply-input">
        <el-input
          type="textarea"
          v-model="replyContent"
          rows="2"
          placeholder="请输入回复内容"
        ></el-input>
        <div class="reply-actions">
          <el-button size="mini" @click="submitReply">提交</el-button>
          <el-button size="mini" @click="cancelReply">取消</el-button>
        </div>
      </div>
    </div>
  </template>
  
  <script>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';

export default {
  name: "CommentItem",
  props: {
    comment: {
      type: Object,
      required: true,
    },
  },
  emits: ["reply"], // 声明发射的事件
  setup(props, { emit }) {
    const showReplyInput = ref(false); // 是否显示回复输入框
    const replyContent = ref(""); // 回复内容
    const username = ref(""); // 用户名

    // 计算属性：格式化时间
    const formattedTime = computed(() => {
      const date = new Date(props.comment.CreatedAt);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    });

    // 根据 userId 获取用户名
    const fetchUsername = async () => {
        const userId = props.comment.user_id; 
        
    
  if (!userId) {
    console.warn("user_id 不存在");
    username.value = "未知用户";
    return;
  }
  try {
    // 发起请求
    const response = await axios.get(`http://localhost:9090/users/${userId}`);
  
    console.log("完整响应数据:", response.data);

    console.log("用户名:", response.data.username); // 检查 response.data
    username.value = response.data?.data?.username || "未知用户"; // 确保正确赋值

  } catch (error) {
   
    console.error("获取用户名失败：", error);
    username.value = "未知用户"; // 请求失败时设置默认值
  }
};


    // 显示/隐藏回复输入框
    const toggleReplyInput = () => {
      showReplyInput.value = !showReplyInput.value;
    };

    // 取消回复
    const cancelReply = () => {
      showReplyInput.value = false;
      replyContent.value = ""; // 清空输入框
    };

    // 提交回复
    const submitReply = () => {
      if (!replyContent.value.trim()) {
        alert("回复内容不能为空！");
        return;
      }
      // 使用 emit 发射事件
      emit("reply", {
        parentId: props.comment.ID, // 子评论的 parentId 是父评论的 ID
        content: replyContent.value.trim(),
      });
      cancelReply(); // 提交后关闭输入框
    };

    // 处理嵌套回复
    const handleNestedReply = (payload) => {
      emit("reply", payload); // 将嵌套回复事件向上传递
    };

    // 在组件加载时，获取用户名
    onMounted(() => {
      fetchUsername();
    });

    return {
      showReplyInput,
      replyContent,
      username,
      formattedTime,
      toggleReplyInput,
      cancelReply,
      submitReply,
      handleNestedReply,
    };
  },
};
</script>


  
  <style scoped>
  .comment {
    margin-bottom: 10px;
    padding: 10px;
    background: #f9f9f9;
    border-radius: 5px;
  }
  
  .nested-comment {
    margin-left: 20px;
    padding-left: 10px;
    border-left: 2px solid #ddd;
  }
  
  .comment-author {
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .comment-time {
    font-size: 12px;
    color: #aaa;
    margin-top: 5px;
  }
  
  .reply-input {
    margin-top: 10px;
  }
  
  .reply-actions {
    margin-top: 5px;
    display: flex;
    gap: 10px;
  }
  </style>
  